package com.gaoyi.crm.fragment.base;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.gaoyi.crm.BR;
import com.gaoyi.crm.callback.IView;
import com.gaoyi.crm.constant.Constants;
import com.gaoyi.crm.control.DateSearchView;
import com.gaoyi.crm.control.DrawableCenterTextView;
import com.gaoyi.crm.db.dto.BaseDto;
import com.gaoyi.crm.db.query.BaseQuery;
import com.gaoyi.crm.vm.base.BaseListViewModel;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.lang.reflect.ParameterizedType;
import java.util.Date;

public abstract class BaseListFragment<V extends ViewDataBinding, VM extends BaseListViewModel<D>, D, Q extends BaseQuery> extends BasePermissionFragment {
    protected FragmentActivity mContext;
    protected V mBinding;
    protected VM mViewModel;
    protected Q mQuery;
    protected NavController mController;
    protected int totalPages;
    protected DateSearchView mDateSearchView;
    protected SearchView mViewSearch;
    protected SmartRefreshLayout mSmartRefreshLayout;
    protected boolean isPause = false; // 切换Fragment标识，避免重复请求数据

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = requireActivity();
        mViewModel = new ViewModelProvider(this).get(getViewModelClass());
        if (this instanceof IView) {
            mViewModel.attachView((IView) this);
        }
        mQuery = createQuery();
        getLifecycle().addObserver(mViewModel);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
        mBinding.setLifecycleOwner(getViewLifecycleOwner());
        mBinding.setVariable(BR.data, mViewModel);
        initView();
        if (mDateSearchView != null) {
            mDateSearchView.setOnSearchClick(this::search);
        }
        if (mViewSearch != null) {
            setSearchView();
        }
        if (mSmartRefreshLayout != null) {
            setSmartRefreshLayout();
        }
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mController = Navigation.findNavController(view);
        initLiveData();
        initData();
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void initLiveData();

    protected abstract void loadData();

    /**
     * 日期搜索
     */
    protected abstract void search(Date startDate, Date endDate);

    protected abstract void search(String keyWord);

    /**
     * 排序点击回调
     * @param id 点击的viewId
     * @param isDesc 排序类型
     */
    protected abstract void sort(int id, Integer isDesc);


    protected abstract Q createQuery();

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.setTag(Constants.REFRESH);
        //刷新
        mSmartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            mSmartRefreshLayout.setTag(Constants.REFRESH);
            if (mQuery != null) {
                mViewModel.clearListValue();
                mQuery.setPageIndex(1);
                loadData();
            }
        });
        //加载更多
        mSmartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            mSmartRefreshLayout.setTag(Constants.LOAD_MORE);
            if (mQuery != null) {
                if (totalPages == 0) {
                    totalPages = 1;
                }
                if (totalPages <= mQuery.getPageIndex())
                    mQuery.setPageIndex(++totalPages);
                else
                    mQuery.setPageIndex(mQuery.getPageIndex() + 1);
                loadData();
            }
        });
    }

    /**
     * 设置搜索框输入监听
     */
    private void setSearchView() {
        mViewSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                search(newText);
                return false;
            }
        });
    }

    /**
     * 设置标题排序点击监听
     */
    protected void serTitleSort(DrawableCenterTextView... textViews) {
        MyOnChangeListener listener = new MyOnChangeListener();
        for (DrawableCenterTextView view : textViews) {
            view.setOnChangeListener(listener);
        }
    }

    private class MyOnChangeListener implements DrawableCenterTextView.OnChangeListener {

        @Override
        public void onChangeListener(int id, Integer sort) {
            sort(id, sort);
        }
    }

    Class<VM> getViewModelClass() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        if (type == null) return null;
        return (Class<VM>) type.getActualTypeArguments()[1];
    }

    @Override
    public void onDestroyView() {
        mBinding.unbind();
        super.onDestroyView();
    }
}
